//
//  PickedImagesView.swift
//  TicketSystem
//
//  Created by ET|冰琳 on 2017/2/14.
//  Copyright © 2017年 UK. All rights reserved.
//

import UIKit
import ReactiveSwift
import ReactiveCocoa

protocol PickerImagesViewImageDataSource{
    func pickerImagesViewWillAdd(_ view: PickerImagesView)
    func pickerImagesView(_ view: PickerImagesView, didAddImage imgs: [ImageInfoProperty])
    
    func pickerImagesView(_ view: PickerImagesView, didDeleteImageAt indexPath: IndexPath)
    func pickerImagesView(_ view: PickerImagesView, imageDidMoveFrom fromIndexPath: IndexPath, toIndexPath: IndexPath)
}

class ImagesCollectionView: UICollectionView {
    
    override var intrinsicContentSize: CGSize {
        let contentSize = self.collectionViewLayout.collectionViewContentSize
        return contentSize
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
    }
}

class PickerImagesView: UIView {

    fileprivate var imagesCollectionView: UICollectionView!
    
    var dataProvider: PickerImagesViewDataProvider!
    var pickerShowFrom: UIViewController?
    var dataSource: PickerImagesViewImageDataSource?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setup()
    }
    
    private func setup() {
        self.imagesCollectionView = ImagesCollectionView(frame: self.bounds, collectionViewLayout: PickerImagesGridLayout())
        self.imagesCollectionView.backgroundColor = UIColor.white
        self.addSubview(self.imagesCollectionView)
        self.imagesCollectionView.delegate = self
        self.imagesCollectionView.dataSource = self
        self.imagesCollectionView.translatesAutoresizingMaskIntoConstraints = false
        
        let horizontal = NSLayoutConstraint.constraints(withVisualFormat: "H:|-images-|", options: NSLayoutFormatOptions.directionLeadingToTrailing, metrics: nil, views: ["images": self.imagesCollectionView]);
        let vertical   = NSLayoutConstraint.constraints(withVisualFormat: "V:|-images-|", options: NSLayoutFormatOptions.alignAllTop, metrics: nil, views: ["images": self.imagesCollectionView]);
        
        self.imagesCollectionView.addConstraints(horizontal)
        self.imagesCollectionView.addConstraints(vertical)
        
        self.imagesCollectionView.register(PickerImagesAddedCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: PickerImagesAddedCollectionViewCell.self))
        self.imagesCollectionView.register(PickerImagesAddCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: PickerImagesAddCollectionViewCell.self))
    }
    
    func reloadData() {
        self.imagesCollectionView.reloadData()
        self.imagesCollectionView.invalidateIntrinsicContentSize()
    }
}

extension PickerImagesView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if indexPath.row < self.dataProvider.images.count {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PickerImagesAddedCollectionViewCell.self),
                                                          for: indexPath) as! PickerImagesAddedCollectionViewCell
            cell.bindWith(self.dataProvider.images[indexPath.row])
            cell.deleteButton.reactive.controlEvents(.touchUpInside)
                .take(until: cell.reactive.prepareForReuse).signal
                .observeValues({ [unowned self] (_) in
                    self.dataProvider.removeImageAt(index: indexPath.row)
                    self.dataSource?.pickerImagesView(self, didDeleteImageAt: indexPath)
                    self.reloadData()
                })
            
            
            return cell
        }
        else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PickerImagesAddCollectionViewCell.self),
                                                          for: indexPath) as! PickerImagesAddCollectionViewCell
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataProvider.numberOfRow()
    }
}

extension PickerImagesView: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        guard let showFrom = self.pickerShowFrom else {
            return
        }
        
        guard dataProvider.images.count == indexPath.row else {
            return
        }
        
        T.pickerImageSignal(fromViewController: showFrom, selectMaxCount: self.dataProvider.maxImageCount - self.dataProvider.images.count)
            .startWithResult { [unowned self] (reslt) in
                guard let value = reslt.value else { return }
                self.dataProvider.addImages(images: value)
                self.dataSource?.pickerImagesView(self, didAddImage: value)
                self.reloadData()
            }
    }
}

// MARK: - 长按拖动 LXReorderableCollectionViewDataSource
extension PickerImagesView: LXReorderableCollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        if indexPath.row == self.dataProvider.images.count {
            return false
        }
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView!, itemAt fromIndexPath: IndexPath!, didMoveTo toIndexPath: IndexPath!) {
        self.dataProvider.changeImage(from: fromIndexPath, to: toIndexPath)
        self.dataSource?.pickerImagesView(self, imageDidMoveFrom: fromIndexPath, toIndexPath: toIndexPath)
    }
    
    func collectionView(_ collectionView: UICollectionView!, itemAt fromIndexPath: IndexPath!, canMoveTo toIndexPath: IndexPath!) -> Bool {
        if toIndexPath.row == self.dataProvider.images.count {
            return false
        }
        return true
    }
}


